package 接雨水;

import java.util.Scanner;

public class Main {
    static int N = 100010;
    static int[] h = new int[N];
    static int[] q = new int[N];

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        for (int i = 1; i <= n; i++) {
            h[i] = in.nextInt();
        }
        int res = 0, tt = 0;
        for (int i = 1; i <= n; i++) {
            int last = 0;
            while (tt > 0 && h[q[tt]] <= h[i]) {
                res += (h[q[tt]] - last) * (i - q[tt] - 1);
                last = h[q[tt]];
                tt--;
            }
            if (tt > 0) {
                res += (h[i] - last) * (i - q[tt] - 1);
            }
            q[++tt] = i;
        }
        System.out.println(res);
    }
}
